import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup

# 配置Chrome选项
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument(
    '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36')

# 替换为你的ChromeDriver路径
chrome_service = ChromeService(executable_path=r"C:\Users\zlsjJSSA\Downloads\chromedriver-win64\chromedriver-win64\chromedriver.exe")

# 初始化WebDriver
driver = webdriver.Chrome(service=chrome_service, options=chrome_options)

# 定义获取评论内容的函数
def get_comments(page_source):
    comments = []
    soup = BeautifulSoup(page_source, 'html.parser')

    # 查找所有评论内容的a标签，根据实际页面结构调整类名
    comment_tags = soup.find_all('a', class_='tap-router tap-router__prefetched')

    for tag in comment_tags:
        comment_text = tag.get_text(strip=True)
        comments.append(comment_text)

    return comments

# 定义主函数，处理评论滚动加载
def main(base_url, max_scrolls):
    all_comments = []
    driver.get(base_url)
    time.sleep(3)  # 等待页面加载

    # 模拟滚动加载更多评论
    for _ in range(max_scrolls):
        # 获取当前页面的评论
        comments = get_comments(driver.page_source)
        if not comments:
            break
        all_comments.extend(comments)

        # 模拟滚动到底部
        driver.find_element(By.TAG_NAME, 'body').send_keys(Keys.END)
        time.sleep(2)  # 等待新评论加载

    # 去重评论
    unique_comments = list(set(all_comments))

    # 保存评论到TXT文件
    with open(r'C:\Users\zlsjJSSA\Desktop\赛尔号评论.txt', 'w', encoding='utf-8-sig') as f:
        for comment in unique_comments:
            f.write(comment + '\n')

    print('评论获取成功！已保存为该游戏评论.txt')

if __name__ == '__main__':
    base_url = 'https://www.taptap.cn/app/46045/review'  # 修改为实际的评论页面URL
    max_scrolls = 10  # 设置最大滚动次数，根据需要调整
    main(base_url, max_scrolls)
    driver.quit()
